package ext.acae2.dms.send;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.ptc.core.meta.common.TypeIdentifierHelper;

import ext.acae2.dms.bean.DataBeanFactory;
import ext.acae2.dms.bean.DocReferenceLinkBean;
import ext.acae2.dms.bean.DocumentBean;
import ext.acae2.dms.bean.EPMDocumentBean;
import ext.acae2.dms.bean.JtBean;
import ext.acae2.dms.bean.PartBean;
import ext.acae2.dms.bean.PartUsageLinkBean;
import ext.acae2.part.PartHelper;
import ext.acae2.util.DownloadUtil;
import ext.acae2.util.FileUtil;
import ext.acae2.util.IBAUtil;
import ext.acae2.util.TCWCMappingDataHelper;
import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentItem;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.content.Streamed;
import wt.doc.WTDocument;
import wt.epm.EPMAuthoringAppType;
import wt.epm.EPMDocument;
import wt.epm.EPMDocumentType;
import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.part.Quantity;
import wt.part.WTPart;
import wt.util.WTException;
import wt.util.WTProperties;
import ext.acae2.dms.bean.DocReferenceLinkBean;
import ext.acae2.dms.bean.DocumentBean;
import ext.acae2.dms.bean.EPMDocumentBean;
import ext.acae2.dms.bean.JtBean;
import ext.acae2.dms.bean.PartBean;
import ext.acae2.dms.bean.PartUsageLinkBean;
import ext.acae2.util.CmIniFileUtil;
import ext.acae2.util.DownloadUtil;
import ext.acae2.util.IBAUtil;
import ext.acae2.util.TCWCMappingDataHelper;

public class DataSendBeanConstruct {

	private static final Logger LOGGER = LogR
			.getLogger(DataSendBeanConstruct.class.getName());

	private static String attrPathFolder;
	public static File exportFile;

	static {
		try {
			String codebasePath = WTProperties.getLocalProperties()
					.getProperty("wt.codebase.location");
		    String tempPath = WTProperties.getLocalProperties().getProperty("wt.temp");
//			attrPathFolder = codebasePath + File.separator + "ext"
//					+ File.separator + "acae2" + File.separator + "dms"
//					+ File.separator + "attr" ;
		    
			attrPathFolder = codebasePath + File.separator + "ext"
					+ File.separator + "acae2" + File.separator + "dms"
					+ File.separator + "output" ;
			
			String exportPath = tempPath+File.separator+"dataExport";
			exportFile = new File(exportPath);
			if(!exportFile.exists()){
				exportFile.mkdirs();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, String> getSendAttrConfigBySupplier(String supplier) throws Exception{
		
		Map<String, String> attrsMap = new HashMap<String, String>();
		String attrFilePath = null;
		attrFilePath = attrPathFolder+File.separator+supplier+".ini";
		
		CmIniFileUtil ini = new CmIniFileUtil(attrFilePath);
		Set<String> keys = ini.getSection("Attr Requird").keySet();
		LOGGER.debug(keys.size());
		for(String key:keys){
			LOGGER.debug("--------------------------"+key);
			String tcAttrName = ini.getSection("Attr Requird").get(key, "");
			LOGGER.debug(tcAttrName);
			LOGGER.debug("**********************************");
			Set<String> attrValueKeys = ini.getSection(key).keySet();
			LOGGER.debug(attrValueKeys.size());
			for(String attrValueKey:attrValueKeys){
				String tcAttrValue = ini.get(attrValueKey, "");
				LOGGER.debug(tcAttrValue);
				attrsMap.put(tcAttrName, tcAttrValue);
			}
			LOGGER.debug("**********************************");
			LOGGER.debug("--------------------------"+key);
		}
		
		return attrsMap;
		
	}
	
	/**
	 * 得到配置需要发送的属性值
	 * @param type
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private static List<String> getSendAttrConfigByType(String type) throws Exception{
		List<String> attrs= new ArrayList<String>();
		String attrFilePath = null;
		if(type.equalsIgnoreCase("doc")){
			attrFilePath = attrPathFolder+File.separator+"docAttrConfig.properties";
		}else if(type.equalsIgnoreCase("epm")){
			attrFilePath = attrPathFolder+File.separator+"epmAttrConfig.properties";
		}else if(type.equalsIgnoreCase("part")){
			attrFilePath = attrPathFolder+File.separator+"partAttrConfig.properties";
		}
		Properties props = new Properties();
		props.load(new FileInputStream(attrFilePath));
		Set<Object> keys = props.keySet();
		@SuppressWarnings("rawtypes")
		Iterator it=keys.iterator();
		while(it.hasNext()){
			String key = (String)it.next();
			if(StringUtils.isNotBlank(key.trim())){
				String value = props.getProperty(key).trim();
				if(StringUtils.equalsIgnoreCase(value.trim(), "Y")){
					attrs.add(key.trim());
				}
				
			}
		}
		return attrs;
	}

	/**
	 * 构造partBean 信息
	 * 
	 * @param part
	 * @return
	 * @throws WTException
	 * @throws RemoteException
	 */
	@SuppressWarnings("unchecked")
	public static PartBean constructPartBean(WTPart part,String path, String supplier) throws Exception {
		LOGGER.debug("构造 PartBean begin=======>" + part.getName() + ":"
				+ part.getNumber());
		Map<String, String> attrMap = new HashMap<String, String>();
		String partNum = part.getNumber();
		String partName = part.getName();
		String version = part.getVersionIdentifier().getValue();
		String iteration = part.getIterationIdentifier().getValue();
		//String prtSource = part.getSource().getStringValue();
		PartBean partBean = new PartBean();
		partBean.setName(partName);
		partBean.setNumber(partNum);
		
		partBean.setPARTTYPE("AE8Part");
		
		partBean.setVersion(version + "." + iteration);
		IBAUtil ibaUtil = new IBAUtil(part);
		
		String attrFilePath = null;
		attrFilePath = attrPathFolder+File.separator+supplier+".ini";
		
		CmIniFileUtil ini = new CmIniFileUtil(attrFilePath);
		Set<String> keys = ini.getSection("Attr Requird").keySet();
		for(String key:keys){
			String tcAttrName = ini.getSection("Attr Requird").get(key, "");
			Set<String> attrValueKeys = ini.getSection(key).keySet();
			LOGGER.debug(attrValueKeys.size());
			
			if(attrValueKeys.size() != 0){
				for(String attrValueKey:attrValueKeys){
					try{
						if(ibaUtil.getIBAValue(key).equals(attrValueKey)){
							String tcAttrValue = ini.get(attrValueKey, "");
							attrMap.put(tcAttrName, tcAttrValue==null?"":tcAttrValue);
						}
					}catch(Exception e){
						//TODO
					}
				}
			}else{
				attrMap.put(tcAttrName,ibaUtil.getIBAValue(key)==null?"":ibaUtil.getIBAValue(key));
			}
			
		}
		
		LOGGER.debug("构造 PartBean end=======>" + part.getName() + ":"
				+ part.getNumber());
		partBean.setMap(attrMap);
		List<JtBean> jtBeans = new ArrayList<JtBean>();
		partBean.setJtList(jtBeans);
		return partBean;
		
		// before start
		
//		List<String> attrs = getSendAttrConfigByType("part");
//		List<JtBean> jtBeans = new ArrayList<JtBean>();
//		for(String attr:attrs){
//			String attrValue = ibaUtil.getIBAValue(attr);
//			if(attrValue==null){
//				attrValue="";
//			}
////			LOGGER.debug("构造 PartBean begin=======>" + attrValue + ":"
////					+ attr);
//			attrMap.put(attr, attrValue);
//			//DataBeanFactory.setPartBeanValue(partBean,StringUtils.upperCase(attr),attrValue);
//		}
//		List<ApplicationData> appDatas = PartHelper.getWVSApplicationData(part); //获取可视话文件
//		if(appDatas==null&&appDatas.size()!=0){
//			for(ApplicationData appData:appDatas){
//				JtBean jtBean = new JtBean();
//				String bussinessType = appData.getBusinessType();
//				String appName = appData.getFileName();
//				String filePath = path+File.separator+appName; //在XML中的path
//				//String locationRef = filePath+","+bussinessType; 
//				jtBean.setLocationRef(filePath);
//				jtBean.setType(bussinessType);
//				jtBeans.add(jtBean);
//			}
//		}
//		LOGGER.debug("构造 PartBean appDatas======================>" + appDatas.size());
//		String locationRef =  +","+appType;
		//
//		LOGGER.debug("构造 PartBean end=======>" + part.getName() + ":"
//				+ part.getNumber());
//		partBean.setMap(attrMap);
//		partBean.setJtList(jtBeans);
//		return partBean;
		
		// before end

	}

	/**
	 * 构造Document的信息
	 * 
	 * @param doc
	 * @return
	 * @throws Exception 
	 */
	@SuppressWarnings("unchecked")
	public static List<DocumentBean> constructDocumentBean(WTDocument doc,String path,String supplier) throws Exception {
		LOGGER.debug("构造 DocumentBean begin=======>" + doc.getName() + ":"
				+ doc.getNumber());
		Map<String,String> attrMap = new HashMap<String,String>();
		
		IBAUtil ibaUtil = new IBAUtil(doc);
		
		String attrFilePath = null;
		attrFilePath = attrPathFolder+File.separator+supplier+".ini";
		
		CmIniFileUtil ini = new CmIniFileUtil(attrFilePath);
		Set<String> keys = ini.getSection("Attr Requird").keySet();
		for(String key:keys){
			String tcAttrName = ini.getSection("Attr Requird").get(key, "");
			Set<String> attrValueKeys = ini.getSection(key).keySet();
			LOGGER.debug(attrValueKeys.size());
			
			if(attrValueKeys.size() != 0){
				for(String attrValueKey:attrValueKeys){
					try{
						if(ibaUtil.getIBAValue(key).equals(attrValueKey)){
							String tcAttrValue = ini.get(attrValueKey, "");
							attrMap.put(tcAttrName, tcAttrValue==null?"":tcAttrValue);
						}
					}catch(Exception e){
						//TODO
					}
				}
			}else{
				attrMap.put(tcAttrName,ibaUtil.getIBAValue(key)==null?"":ibaUtil.getIBAValue(key));
			}
			
		}
		
		// before start
		
//		List<String> attrs = getSendAttrConfigByType("doc");
//		Map<String,String> attrMap = new HashMap<String,String>();
//		for(String attr:attrs){
//			String attrValue = ibaUtil.getIBAValue(attr);
//			if(attrValue==null){
//				attrValue="";
//			}
//			attrMap.put(attr, attrValue);
//			//DataBeanFactory.setDocBeanValue(docBean,StringUtils.upperCase(attr),attrValue);
//		}
		
		// before end
		
		List<DocumentBean> docBeanList = new ArrayList<DocumentBean>();
		
		QueryResult qr = ContentHelper.service.getContentsByRole(doc, ContentRoleType.SECONDARY);
		QueryResult qr1 = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
		qr.append(qr1.getObjectVectorIfc());
		//LOGGER.debug("文件个数（包含附件和主内容）===============>" + qr.size());
		List<String> locationRefList= new ArrayList<String>();
		while(qr.hasMoreElements()){
			String partNum = doc.getNumber();
			String partName = doc.getName();
			String version = doc.getVersionIdentifier().getValue();
			String iteration = doc.getIterationIdentifier().getValue();
			DocumentBean docBean = new DocumentBean();
			docBean.setName(partName);
			docBean.setNumber(partNum);
			
			docBean.setDOCUMENTTYPE("Document");
			
			docBean.setVersion(version + "." + iteration);
			docBean.setMap(attrMap);
			String description = doc.getDescription();
			docBean.setDescription(description);
			
			ContentItem contentitem = (ContentItem) qr.nextElement();
			ApplicationData applicationdata = (ApplicationData) contentitem;
			String appType = applicationdata.getBusinessType();
			String appFileName = applicationdata.getFileName();
			String filePath = path+"\\"+appFileName; //在XML中的path
//			File dataFolder = new File(exportFile.getAbsolutePath()+File.separator+path+File.separator+path);
//			FileUtil.deleteDir(dataFolder);
//			dataFolder.mkdirs();
			
			DownloadUtil.download(applicationdata, exportFile.getAbsolutePath()+File.separator+supplier+File.separator+path+File.separator+path+File.separator+appFileName);
			String wcType = appFileName.substring(appFileName.lastIndexOf(".")+1);
			String tcType = TCWCMappingDataHelper.getTCWCMapping(TCWCMappingDataHelper.TYPE_MAPPING_CONFIG, wcType);
			LOGGER.debug("构造 DocumentBean appType=======>" + appType+"::::::"+appFileName+":::::::"+filePath);
			String locationRef = filePath +","+tcType;
			locationRefList.add(locationRef);
			docBean.setLocationRefList(locationRefList);
			
			docBeanList.add(docBean);
		}
		
		LOGGER.debug("构造 DocumentBean end=======>" + doc.getName() + ":"
				+ doc.getNumber());
		return docBeanList;

	}

	/**
	 * 构造EPM信息
	 * 
	 * @param epm
	 * @return
	 * @throws Exception 
	 */
	public static Map constructEPMDocumentBean(EPMDocument epm,String path,String supplier) throws Exception {
		LOGGER.debug("构造 EPMDocumentBean begin=======>" + epm.getName() + ":"
				+ epm.getNumber());
		
		Map map = new HashMap();
		
		EPMDocumentBean epmBean = new EPMDocumentBean();
		String epmType = epm.getType();
		String epmNum = epm.getNumber();
		String epmName = epm.getName();
		//LOGGER.debug("构造 EPMDocumentBean epm.getType();=======>" + epmType);
		String version = epm.getVersionIdentifier().getValue();
		String iteration = epm.getIterationIdentifier().getValue();
		EPMDocumentType docType = epm.getDocType();
		EPMAuthoringAppType authAppType = epm.getAuthoringApplication();
		epmBean.setNumber(epmNum);
		epmBean.setName(epmName);
		epmBean.setVersion(version + "." + iteration);
		
		QueryResult qr = ContentHelper.service.getContentsByRole(epm, ContentRoleType.PRIMARY);
		while(qr.hasMoreElements()){
			ContentItem contentitem = (ContentItem) qr.nextElement();
			ApplicationData applicationdata = (ApplicationData) contentitem;
			//String appType = applicationdata.getBusinessType();
			String appFileName = applicationdata.getFileName();
			String filePath = path+"\\"+epm.getCADName();//在XML中的path
//			File dataFolder = new File(exportFile.getAbsolutePath()+File.separator+path+File.separator+path);
//			FileUtil.deleteDir(dataFolder);
//			dataFolder.mkdirs();
			DownloadUtil.download(applicationdata, exportFile.getAbsolutePath()+File.separator+supplier+File.separator+path+File.separator+path+File.separator+epm.getCADName());
			String appType="UGMASTER";
			if(EPMAuthoringAppType.toEPMAuthoringAppType("ACAD").equals(authAppType)){
				appType = "AutoCAD";
			}else{
				if(EPMDocumentType.toEPMDocumentType("CADASSEMBLY").equals(docType)||
						EPMDocumentType.toEPMDocumentType("CADCOMPONENT").equals(docType)){
					appType = "UGMASTER";
				}else if(EPMDocumentType.toEPMDocumentType("CADDRAWING").equals(docType)){
					appType = "UGPART";
				}
			}
			//appType = TCWCMappingDataHelper.getTCWCMapping(TCWCMappingDataHelper.TYPE_MAPPING_CONFIG, appType);
			LOGGER.debug("构造 EPMDocumentBean appType=======>" + appType+"::::::"+appFileName+":::::::"+filePath);
			String locationRef = filePath +","+appType;
			epmBean.setLocationRef(locationRef);
		}
		
		Map<String,String> attrMap = new HashMap<String,String>();
		
		IBAUtil ibaUtil = new IBAUtil(epm);
		
		String attrFilePath = null;
		attrFilePath = attrPathFolder+File.separator+supplier+".ini";
		
		CmIniFileUtil ini = new CmIniFileUtil(attrFilePath);
		Set<String> keys = ini.getSection("Attr Requird").keySet();
		for(String key:keys){
			String tcAttrName = ini.getSection("Attr Requird").get(key, "");
			Set<String> attrValueKeys = ini.getSection(key).keySet();
			LOGGER.debug(attrValueKeys.size());
			
			if(attrValueKeys.size() != 0){
				for(String attrValueKey:attrValueKeys){
					try{
						if(ibaUtil.getIBAValue(key).equals(attrValueKey)){
							String tcAttrValue = ini.get(attrValueKey, "");
							attrMap.put(tcAttrName, tcAttrValue==null?"":tcAttrValue);
						}
					}catch(Exception e){
						//TODO
					}
				}
			}else{
				attrMap.put(tcAttrName,ibaUtil.getIBAValue(key)==null?"":ibaUtil.getIBAValue(key));
			}
			
		}
		
		QueryResult qr1 = ContentHelper.service.getContentsByRole(epm, ContentRoleType.SECONDARY);
		//LOGGER.debug("文件个数（包含附件和主内容）===============>" + qr.size());
		List<String> locationRefList= new ArrayList<String>();
		DocumentBean docBean = null;
		while(qr1.hasMoreElements()){
			docBean = new DocumentBean();
			String partNum = epm.getNumber();
			String partName = epm.getName();
			String version1 = epm.getVersionIdentifier().getValue();
			String iteration1 = epm.getIterationIdentifier().getValue();
			
			docBean.setName(partName);
			docBean.setNumber(partNum);
			docBean.setVersion(version1 + "." + iteration1);
			docBean.setMap(attrMap);
			String description = epm.getDescription();
			docBean.setDescription(description);
			
			ContentItem contentitem = (ContentItem) qr1.nextElement();
			ApplicationData applicationdata = (ApplicationData) contentitem;
			String appType = applicationdata.getBusinessType();
			String appFileName = applicationdata.getFileName();
			String filePath = path+"\\"+appFileName; //在XML中的path
//			File dataFolder = new File(exportFile.getAbsolutePath()+File.separator+path+File.separator+path);
//			FileUtil.deleteDir(dataFolder);
//			dataFolder.mkdirs();
			
			DownloadUtil.download(applicationdata, exportFile.getAbsolutePath()+File.separator+supplier+File.separator+path+File.separator+path+File.separator+appFileName);
			String wcType = appFileName.substring(appFileName.lastIndexOf(".")+1);
			String tcType = TCWCMappingDataHelper.getTCWCMapping(TCWCMappingDataHelper.TYPE_MAPPING_CONFIG, wcType);
			LOGGER.debug("构造 DocumentBean appType=======>" + appType+"::::::"+appFileName+":::::::"+filePath);
			String locationRef = filePath +","+tcType;
			locationRefList.add(locationRef);
			docBean.setLocationRefList(locationRefList);
			
		}
		
		map.put("epm", epmBean);
		map.put("doc", docBean);
		
		LOGGER.debug("构造 EPMDocumentBean end=======>" + epm.getName() + ":"
				+ epm.getNumber());
		return map;

	}
	
	
	/**
	 * 构造part和文档之间的关系
	 * @param partBean
	 * @param docBean
	 * @return
	 */
	public static DocReferenceLinkBean constructDocRefLinkBean(PartBean partBean,DocumentBean docBean){
		DocReferenceLinkBean docLinkBean = new DocReferenceLinkBean(partBean,docBean);
		return docLinkBean;
	}
	
	
	/**
	 * 构造part与part之间的关系
	 * @param parentPartBean
	 * @param childPartBean
	 * @param quantity
	 * @return
	 */
	public static PartUsageLinkBean constructPartUsageLinkBean(
			PartBean parentPartBean, PartBean childPartBean, Quantity quantity) {
		PartUsageLinkBean partUsageLinkBean = null;
		if (quantity != null) {
			partUsageLinkBean = new PartUsageLinkBean();
			partUsageLinkBean.setChildPart(childPartBean);
			partUsageLinkBean.setParentPart(parentPartBean);
			double singleQuantity = quantity.getAmount();
			String qunitStr = quantity.getUnit().getStringValue();
			String singleStr = String.valueOf(singleQuantity);
			partUsageLinkBean.setSingleAmout(Integer.parseInt(singleStr.substring(0,singleStr.lastIndexOf("."))));
			partUsageLinkBean.setUnitStr(qunitStr);
			LOGGER.debug("constructPartUsageLinkBean=========>"+qunitStr+":::::::"+singleQuantity);
		}
		return partUsageLinkBean;
	}

}
